package com.tarena.lbs.util;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtils {

    public static String saveFile(MultipartFile file, String uploadDir) throws IOException {
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        String originalFilename = file.getOriginalFilename();
        String fileExtension = FilenameUtils.getExtension(originalFilename);
        String uniqueFileName = UUIDGenerator.generate() + "." + fileExtension;

        Path filePath = Paths.get(uploadDir, uniqueFileName);
        Files.write(filePath, file.getBytes());

        return uniqueFileName;
    }
    public static String getFileExtension(String filename) {
        return FilenameUtils.getExtension(filename);
    }

    public static boolean deleteFile(String filePath) {
        return new File(filePath).delete();
    }

    public static String getFileType(MultipartFile file) {
        return file.getContentType();
    }
}
